package com.example.mode.activity;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import com.example.mode.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class CountdownActivity extends AppCompatActivity {

    private TextView countdownTextView;
    private DatePicker datePicker;
    private Button startCountdownButton;
    private CountDownTimer countDownTimer;
    private static final String CHANNEL_ID = "CountdownChannel";
    private static final int NOTIFICATION_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_countdown);

        countdownTextView = findViewById(R.id.countdown_text);
        datePicker = findViewById(R.id.date_picker);
        startCountdownButton = findViewById(R.id.start_countdown_button);

        startCountdownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startCountdown();
            }
        });
    }

    private void startCountdown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
        Date targetDate = calendar.getTime();
        long targetMillis = targetDate.getTime();
        long currentMillis = System.currentTimeMillis();
        long diffMillis = targetMillis - currentMillis;

        if (diffMillis > 0) {
            countDownTimer = new CountDownTimer(diffMillis, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    long days = millisUntilFinished / (1000 * 60 * 60 * 24);
                    long hours = (millisUntilFinished % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
                    long minutes = (millisUntilFinished % (1000 * 60 * 60)) / (1000 * 60);
                    long seconds = (millisUntilFinished % (1000 * 60)) / 1000;

                    String countdownStr = String.format(Locale.getDefault(), "%d 天 %d 小时 %d 分 %d 秒", days, hours, minutes, seconds);
                    countdownTextView.setText(countdownStr);
                }

                @Override
                public void onFinish() {
                    countdownTextView.setText("倒计时结束！");
                    sendNotification();
                }
            }.start();
        } else {
            Toast.makeText(this, "选择的日期已过去，请重新选择", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Countdown Channel", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        Intent intent = new Intent(this, CountdownActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("倒计时结束")
                .setContentText("您设置的倒计时已经结束啦！")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        Notification notification = builder.build();
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    public void shareCountdown(View view) {
        String countdownText = countdownTextView.getText().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
        String targetDateStr = sdf.format(calendar.getTime());

        String shareText = "我设置的到 " + targetDateStr + " 的倒计时还有：" + countdownText;
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
        startActivity(Intent.createChooser(shareIntent, "分享倒计时信息"));
    }
}